import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { env } from '../../environments/index';
interface Reply {
  code: number;
  data: object;
  msg: string;
}
@Injectable({
  providedIn: 'root'
})
export class NetService {
  private url = env.host;
  constructor(
    private http: HttpClient,
  ) {}

  private handleUrl(url: string) {
    if (url.startsWith('http://') || url.startsWith('https://')) {
      return url;
    } else {
      return this.url + url;
    }
  }

  public get(url: string, options: object = {}) {
    return new Promise((resolve, reject) => {
      this.http.get(this.handleUrl(url), options).subscribe(
        (res: Reply) => {
          if (res && res.code === 1) {
            resolve(res);
          } else {
            resolve(null);
          }
        },
        error => resolve(null)
      );
    });
  }

  public post(url: string, data: object, options: object = {}) {
    return new Promise((resolve, reject) => {
      this.http.post(this.handleUrl(url), data, options).subscribe(
        (res: Reply) => {
          if (res && res.code === 1) {
            resolve(res);
          } else {
            resolve(null);
          }
        },
        error => resolve(null)
      );
    });
  }

  public delete(url: string, options: object = {} ) {
    return new Promise(async (resolve, reject) => {
      this.http.delete(this.handleUrl(url), options).subscribe(
        (res: Reply) => {
          if (res && res.code === 1) {
            resolve(res);
          } else {
            resolve(null);
          }
        },
        error => resolve(null)
      );
    });
  }

  public put(url: string, data: object, options: object = {}) {
    return new Promise((resolve, reject) => {
      this.http.put(this.handleUrl(url), data, options).subscribe(
        (res: Reply) => {
          if (res && res.code === 1) {
            resolve(res);
          } else {
            resolve(null);
          }
        },
        error => resolve(null)
      );
    });
  }
}
